// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.io.jdom;

import org.jdom.Attribute;
import org.jdom.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Wrap a JDom element for easy access.
 *
 * @author jessewilson
 */
public class EasyElement {

  private final Element element;

  public EasyElement(Element element) {
    assert(element != null);
    this.element = element;
  }

  public EasyElement(String name) {
    this(new Element(name));
  }

  public String getString(String key, String defaultValue) {
    Attribute attribute = element.getAttribute(key);
    if (attribute == null) {
      return defaultValue;
    }
    return attribute.getValue();
  }

  public int getInt(String key, int defaultValue) {
    Attribute attribute = element.getAttribute(key);
    if (attribute == null) {
      return defaultValue;
    }
    try {
      return Integer.parseInt(attribute.getValue());
    } catch (NumberFormatException e) {
      Logger.getLogger(EasyElement.class.getName())
          .log(Level.WARNING, "Failed to parse \"" + attribute.getValue() + "\" as an integer", e);
      return defaultValue;
    }
  }

  public boolean getBoolean(String key, boolean defaultValue) {
    Attribute attribute = element.getAttribute(key);
    if (attribute == null) {
      return defaultValue;
    }
    return Boolean.parseBoolean(attribute.getValue());
  }


  public void putString(String key, String value) {
    if(value != null) {
      element.setAttribute(key, value);
    } else {
      element.removeAttribute(key);
    }
  }

  public void putInt(String key, int value) {
    putString(key, "" + value);
  }

  public void putBoolean(String key, boolean value) {
    putString(key, String.valueOf(value));
  }

  public void addChild(EasyElement childConfig) {
    element.addContent(childConfig.element);
  }

  public List<EasyElement> getChildren() {
    List<EasyElement> result = new ArrayList<EasyElement>();
    for (Element child : (List<Element>)element.getChildren()) {
      result.add(new EasyElement(child));
    }
    return result;
  }

  public Element getElement() {
    return element;
  }
}
